/*
 * @(#)VerifyCodeFilter.java 2020-07-09
 *
 * Copyright (c) 2010 by rayootech.com. All rights reserved.
 */
package com.nuctech.formlogin.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * SpringSecurity验证码过滤器
 *
 * @author lilu
 * @date 2020-07-09
 * @since 1.0.0
 */
@Component
public class VerifyCodeFilter extends GenericFilter {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		if ("POST".equals(request.getMethod()) && "/doLogin".equals(request.getServletPath())) {
			// 仅拦截登录请求
			String code = request.getParameter("code");
			Object verifyCode = request.getSession().getAttribute("verify_code");
			if (StrUtil.isBlank(code) || ObjectUtil.isEmpty(verifyCode) || !verifyCode.toString().equalsIgnoreCase(code)) {
				response.setContentType(ContentType.JSON.toString(StandardCharsets.UTF_8));
				PrintWriter out = response.getWriter();
				out.write(new ObjectMapper().writeValueAsString("验证码错误！"));
				out.flush();
				out.close();
				return;
			} else {
				filterChain.doFilter(request, response);
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}

}
